package com.ruoyi.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipOutputStream;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.domain.QueryT09VO;
import com.ruoyi.entity.Ftp;

import com.ruoyi.service.IT03Service;
import com.ruoyi.uitity.MinioUtil;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.domain.T09;
import com.ruoyi.common.result.Result;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.service.IT09Service;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

/**
 * 知识库管理Controller
 *
 * @author ruoyi
 * @date 2024-07-25
 */
@RestController
@RequestMapping("/knowledge_manage/T09")
public class T09Controller extends BaseController
{
    @Autowired
    private IT09Service t09Service;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private IT03Service t03Service;
//    @Autowired
//    private MinioUtil minioUtil;

    private static final String FTP_HOST = "47.121.118.149";
    private static final int FTP_PORT = 21;
    private static final String FTP_USER = "peace";
    private static final String FTP_PASSWORD = "123456";
    private static final String FTP_UPLOAD_PATH ="/data/ftp";
    private static String LOCAL_CHARSET = "GBK";
    /**
     * 查询知识库管理列表
     */
    @PreAuthorize("@ss.hasPermi('knowledge_manage:T09:list')")
    @ApiOperation("查询")
    @GetMapping("/list")
    public TableDataInfo list(T09 t09)
    {
        startPage();
        List<T09> list = t09Service.selectT09List(t09);
        return getDataTable(list);
    }
    /**
     * 导出知识库管理列表
     */
    @PreAuthorize("@ss.hasPermi('knowledge_manage:T09:export')")
    @Log(title = "知识库管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, T09 t09)
    {
        List<T09> list = t09Service.selectT09List(t09);
        ExcelUtil<T09> util = new ExcelUtil<T09>(T09.class);
        util.exportExcel(response, list, "知识库管理数据");
    }

    /**
     * 获取知识库管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('knowledge_manage:T09:query')")
    @GetMapping(value = "/{F0901}")
    public AjaxResult getInfo(@PathVariable("F0901") Long F0901)
    {
        return success(t09Service.selectT09ByF0901(F0901));
    }

    /**
     * 新增知识库管理
     */
    @PreAuthorize("@ss.hasPermi('knowledge_manage:T09:add')")
    @Log(title = "知识库管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody T09 t09)
    {
        return toAjax(t09Service.insertT09(t09));
    }

    /**
     * 修改知识库管理
     */
    @PreAuthorize("@ss.hasPermi('knowledge_manage:T09:edit')")
    @Log(title = "知识库管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody T09 t09)
    {
        return toAjax(t09Service.updateT09(t09));
    }

    /**
     * 删除知识库管理
     */
    @PreAuthorize("@ss.hasPermi('knowledge_manage:T09:remove')")
    @Log(title = "知识库管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{F0901s}")
    public AjaxResult remove(@PathVariable Long[] F0901s)
    {
        return toAjax(t09Service.deleteT09ByF0901s(F0901s));
    }

    /*
    知识库上传
     */
    @PostMapping(value = "/fileUpload", consumes = {"multipart/form-data"})
    @ApiOperation("文件上传")
    public Result fileUpload(@RequestPart("/files") List<MultipartFile> files, HttpServletRequest request) throws IOException {
        if (files == null || files.isEmpty()) {
            return new Result("没有文件被上传");
        }
        StringBuilder result = new StringBuilder("文件上传结果：\n");
        FTPClient ftpClient = new FTPClient();
        ftpClient = Ftp.init();
        try {
            LoginUser loginUser =tokenService.getLoginUser(request);
            Long userId=loginUser.getUserId();
            List<String> uploadList = new java.util.ArrayList<>();
            for (MultipartFile file : files) {
                T09 t09 = Ftp.upload(file, ftpClient);
                if(t09!=null){
                    t09.setF1801(userId);
                    String res="文件："+t09.getF0902()+"上传成功";
                    uploadList.add(res);
                    t09Service.insertT09(t09);
                }
                String res = "文件："+file.getOriginalFilename()+"上传失败";
            }
            ftpClient.logout();
            return Result.success(uploadList,"上传成功");
        } catch (IOException e) {
            result.append(" 上传失败: ").append(e.getMessage());
            return Result.erro(result.toString());
        } finally {
            if(ftpClient!=null && ftpClient.isConnected())
                try {
                    ftpClient.disconnect();
                }catch (IOException e){
                    result.append("FTP连接失败: ").append(e.getMessage());
                }
        }
    }
    /*
    知识库下载
     */
//    @PreAuthorize("@ss.hasPermi('knowledge_manage:T09:download')")
    @GetMapping("/download")
    @ResponseBody
    @ApiImplicitParam(name = "F0901s", value = "F0901s", allowMultiple = true, dataTypeClass = List.class, paramType = "query")
    @ApiOperation("知识库下载")
    public ResponseEntity<StreamingResponseBody> fileDownload(@RequestParam("F0901s") List<Long> F0901s, HttpServletResponse response) throws Exception {
        if (F0901s == null || F0901s.isEmpty()) {
            return ResponseEntity.badRequest().body(out -> out.write("没有指定文件ID".getBytes("UTF-8")));
        }
        System.out.println(F0901s);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        String format = sdf.format(date);
        headers.setContentDispositionFormData("attachment", format+".zip");
        StreamingResponseBody body = out -> {
            try (ZipOutputStream zipOut = new ZipOutputStream(out)) {
                for (Long fileId : F0901s) {
                    FTPClient ftpClient = Ftp.init();
                    ftpClient.enterLocalPassiveMode();
                    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    T09 fileRecord = t09Service.selectT09ByF0901(fileId);
                    System.out.println(fileRecord.getF0902());
                    if (fileRecord != null) {
                        String filePath = fileRecord.getF0908();
                        String fileName = fileRecord.getF0902();
                        System.out.println("path=============" + filePath);
                        try  {
                            InputStream inputStream = ftpClient.retrieveFileStream(filePath);
                            if (inputStream != null) {
                                ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileName);
                                zipOut.putNextEntry(zipEntry);
                                IOUtils.copy(inputStream, zipOut);
                                zipOut.closeEntry();
                                System.out.println("1");
                            }
                        } catch (IOException e) {
                            // 记录异常
                            throw new RuntimeException(e);
                        }
                    }
                }
                out.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        };
        return ResponseEntity.ok().headers(headers).body(body);
    }
    @PostMapping("/T09/updatefile")
    public AjaxResult updatefile(MultipartFile file,HttpServletRequest request){
        Long userId = tokenService.getLoginUser(request).getUser().getUserId();
        String filename = UUID.randomUUID().toString();
        boolean flag = t09Service.upload(userId,file, filename);
        if (flag){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
    @Autowired
    private MinioUtil minioUtil;
    @GetMapping("/down/{F0901}")
    public void down(@PathVariable("F0901") Long F0901, HttpServletResponse response) {
        try {
            T09 t09 = t09Service.selectT09ByF0901(F0901);
            if (t09 == null || t09.getF0908() == null) {
                throw new RuntimeException("文件不存在");
            }
            String filename = t09.getF0908();
            minioUtil.downloadAsZip(response, filename);
        } catch (Exception e) {
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("文件下载失败：" + e.getMessage());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

